package gui.mainframe;

import gui.catalogues.colors.ColorFormEvent;
import gui.catalogues.colors.interfaces.ColorFormListener;
import gui.catalogues.colors.models.ColorFormPanel;
import gui.catalogues.customElements.TablePanel;
import gui.catalogues.persons.PersonDTO;
import gui.catalogues.persons.PersonFormListener;
import gui.catalogues.persons.PersonFormPanel;
import gui.catalogues.persons.PersonTableModel;
import gui.catalogues.persons.PersonTablePanel;
import gui.catalogues.persons.interfaces.PersonTableListener;
import gui.catalogues.products.ProductFormEvent;
import gui.catalogues.products.ProductFormListener;
import gui.catalogues.products.ProductFormPanel;
import gui.catalogues.sizes.SizeFormEvent;
import gui.catalogues.sizes.SizeFormListener;
import gui.catalogues.sizes.SizeFormPanel;
import gui.commons.TextPanel;
import gui.commons.ToolbarListener;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.sql.SQLException;
import java.util.prefs.Preferences;

import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JSplitPane;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import org.apache.log4j.Logger;

import controller.GeneralController;
import controller.PersonController;

/*
 *	MainFrame is my customized version of a JFrame which 
 *	has already all my modifications.
 *
 *	Should be seen as the Controller Module of the application since it integrates all the 
 *	components and manages their interactions.
 * 
 * */

public class MainFrame extends JFrame {

	/**
	 * serialVersion for this and only this class
	 */
	private static final long serialVersionUID = 4443562935096594681L;

	/*
	 * logger
	 */
	private final static Logger logger = Logger.getLogger(MainFrame.class);

	/*
	 * Variable declaration
	 */
	private TextPanel textPanel;
	private TablePanel tablePanel;
	private MainFrameToolbar mainFrameToolbar;
	// tabbed pane for the forms
	// private JTabbedPane jtpFormsPane;
	private CustomJTabbedPane jtpFormsPane;
	// tabbed pane identifiers
	private String classToCall = "NA", tabDesc = "NA";
	private int tabIndex = -1;
	// forms
	private PersonFormPanel personFormPanel;
	private ColorFormPanel colorFormPanel;
	private SizeFormPanel sizeFormPanel;
	private ProductFormPanel productFormPanel;
	private JSplitPane splitPane;

	private PersonTablePanel personTablePanel;

	/*
	 * MenuBar variables declaration
	 */
	private JMenuBar jmb;
	// menus contained
	private JMenu jmFile, jmWindow, jmCatalogues, jmEdit;
	// items that menus contain
	private JMenuItem jmiImport, jmiExport, jmiExit, jmiPreferences;
	// private JCheckBoxMenuItem jmiPersonFP, jmiProductFP, jmiSizeFP,
	// jmiColorFP;
	private final JCheckBoxMenuItem jmiPersonFP = new JCheckBoxMenuItem(
			"Personas"), jmiProductFP = new JCheckBoxMenuItem("Productos"),
			jmiSizeFP = new JCheckBoxMenuItem("Tallas"),
			jmiColorFP = new JCheckBoxMenuItem("Colores ");
	// fileChooser for the bar items
	private JFileChooser fcMainFrame;

	/*
	 * Credentials' variables declaration
	 */
	// set to true to skip
	private boolean pasa = false;
	private String uname = "", psswd = "";

	/*
	 * Controller
	 */
	PersonController personController;
	GeneralController generalController;

	/*
	 * Preferences Dialog
	 */
	PreferencesDialog prefsDiag;
	String strUname, strUpass;
	int iPort;
	// loading default preferences
	private Preferences prefs;

	/*
	 * DB related variables
	 */
	private int maxId;

	public MainFrame() {
		super("Ventana Principal");

		try {
			// UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
			// UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
			UIManager
					.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");

		} catch (Exception e) {
			System.out.println("LookAndFeel Exception: " + e);
		}

		while (true) {
			// TODO skipping validation while testing other stuff, must replace
			// pasa = validaUsuarioYPass();
			pasa = true;
			if (pasa) {
				initVariables();
				manageLayout();
				manageListeners();
				// stop the eternal cycle
				break;
			}
		}
	}

	/*
	 * Variable initialization
	 */
	public void initVariables() {
		// the controllers go first!
		personController = new PersonController();
		generalController = new GeneralController();
		textPanel = new TextPanel();
		tablePanel = new TablePanel(new PersonTableModel());
		mainFrameToolbar = new MainFrameToolbar();
		personFormPanel = new PersonFormPanel();
		colorFormPanel = new ColorFormPanel();
		sizeFormPanel = new SizeFormPanel();
		productFormPanel = new ProductFormPanel();
		jtpFormsPane = new CustomJTabbedPane();
		
		personTablePanel = new PersonTablePanel();
		personTablePanel.setTableData(personController.getPeopleList());

		/*
		 * Init menu bar
		 */
		jmb = new JMenuBar();
		// menus contained
		jmFile = new JMenu("Archivo");
		jmEdit = new JMenu("Edición");
		jmWindow = new JMenu("Ventana");
		jmCatalogues = new JMenu("Catálogos");
		// items that menus contain
		jmiImport = new JMenuItem("Importar...");
		jmiExport = new JMenuItem("Exportar...");
		jmiExit = new JMenuItem("Salir.");
		jmiPreferences = new JMenuItem("Preferencias");

		// I set one item selected by default
		jmiPersonFP.setSelected(true);
		// menu file adds open and exit items
		jmFile.add(jmiImport);
		jmFile.add(jmiExport);
		jmFile.addSeparator();
		jmFile.add(jmiExit);
		// menu edit
		jmEdit.add(jmiPreferences);
		// menu catalogues adds color, person, product and size items
		jmCatalogues.add(jmiColorFP);
		jmCatalogues.add(jmiPersonFP);
		jmCatalogues.add(jmiProductFP);
		jmCatalogues.add(jmiSizeFP);
		// menu window adds catalogues
		jmWindow.add(jmCatalogues);
		// menubar adds file and window menus
		jmb.add(jmFile);
		jmb.add(jmEdit);
		jmb.add(jmWindow);

		// init fileChooser
		fcMainFrame = new JFileChooser();

		/*
		 * Prefs dialogue w/window source, title and modal option (true for not
		 * allowing to do anything else until closing the dialogue. false, if
		 * desired the opposite)
		 */
		prefsDiag = new PreferencesDialog(this, "Preferencias", true);

		// preferences default loader
		prefs = Preferences.userRoot().node("pasarellePOS");

		// setting the preference defaults
		strUname = prefs.get("user", "");
		strUpass = prefs.get("password", "");
		iPort = prefs.getInt("port", 3306);

		prefsDiag.setDefaults(strUname, strUpass, iPort);
		prefsDiag.exportPreferences(prefs, "prefs.xml");

		/*
		 * Menu mnemonics. Mnemonics are shortcuts for the menubar with Alt +
		 * Key combinations
		 */
		jmFile.setMnemonic(KeyEvent.VK_A);
		jmWindow.setMnemonic(KeyEvent.VK_V);
		jmCatalogues.setMnemonic(KeyEvent.VK_C);
		jmiExit.setMnemonic(KeyEvent.VK_S);

		/*
		 * Menu accelerators. Accelerators are shortcuts that don't need the
		 * menubar to display for the commands to be activated, i.e. with the
		 * Ctrl + some key
		 */
		jmiExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
				ActionEvent.CTRL_MASK));
		jmiExport.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
				ActionEvent.CTRL_MASK));
		jmiImport.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I,
				ActionEvent.CTRL_MASK));
		jmiPreferences.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
				ActionEvent.CTRL_MASK));
	}

	public void manageLayout() {
		// layout
		setLayout(new BorderLayout());

		/*
		 * Adding components to the window
		 */
		// setMenuBar
		setJMenuBar(jmb);
		// then the icons toolbar
		add(mainFrameToolbar, BorderLayout.PAGE_START);

		// I add the form panels to the tabbed pane
		jtpFormsPane.add("Colores", colorFormPanel);
		jtpFormsPane.add("Personas", personFormPanel);
		jtpFormsPane.add("Productos", productFormPanel);
		jtpFormsPane.add("Tallas", sizeFormPanel);

		// I set the default selection to the person form
		jtpFormsPane.setSelectedComponent(personFormPanel);
		// register which tab is selected at the beggining
		setTabByIndex();

		// I merge vertically the formsPanel with the tpTable into the splitPane
		splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jtpFormsPane, tablePanel);
				//personTablePanel);
		// Enables little arrows to expand the split to either side
		splitPane.setOneTouchExpandable(true);

		// I add the splitPane to the center area
		add(splitPane, BorderLayout.CENTER);

		// finally, I add the textPanel to the south area
		add(textPanel, BorderLayout.SOUTH);

		/*
		 * 2013.03.15 new windowListener that will check when the window closes
		 * and will release the db connections as well as closing all the
		 * processes
		 */
		addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent e) {
				logger.info("Windows and connections closing.");
				// System.out.println("Windows and connections closing.");
				try {
					// personController.cDisconnectFromDB();
					generalController.disconnectFromDB();
					generalController.stopDB();
				} catch (SQLException e1) {
					// System.out
					// .println("SQLException while trying to exit the application: "
					// + e);
					logger.error("SQLException while trying to exit the application: "
							+ e);
				}
				// dispose window
				dispose();
				// call garbage collector
				System.gc();
			}

		});
		// make frame visible
		setVisible(true);
		// make frame close the process as it exits the window as well
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // will be kept as
																// do nothing by
																// the time,
																// cause i'm
																// implementing
																// a customized
																// event
		// set window minimum and actual dimensions
		Dimension dim = new Dimension(1150, 650);
		setSize(dim);
		setMinimumSize(new Dimension((int) (dim.width * .8),
				(int) (dim.height * .8)));

	}

	public void manageListeners() {
		// assign 'tBar' to listen to the toolbar's clicks
		mainFrameToolbar.setToolbarListener(new ToolbarListener() {

			@Override
			public void saveItemEventOccured() {
				System.out.println("Mainframe's saveEventOccured.");
				// connect();
				//
				// try {
				// personController.savePeopleToDB();
				// } catch (SQLException e) {
				// JOptionPane.showMessageDialog(MainFrame.this,
				// "Problem saving to database.", "DB saving problem",
				// JOptionPane.ERROR_MESSAGE);
				// }
			}

			@Override
			public void refreshCollectionEventOccured() {
				connect();

				try {
					personController.loadPeopleFromDB();
				} catch (SQLException e) {
					JOptionPane.showMessageDialog(MainFrame.this,
							"Problem loading from database.",
							"DB loading problem", JOptionPane.ERROR_MESSAGE);
				}
				personTablePanel.refresh();
			}

			@Override
			public void addItemEventOccured() {
				connect();

				/*
				 * 1.- Process which tab am I in.
				 */
				setTabByIndex();
				// System.out.println("I'm on tab: " +
				// try {
				if (jtpFormsPane.getClassToCall().equals("Person")) {
					// personController.loadPeopleFromDB();
					// maxId = personController.getPeoplesMaxId();
					// } else {
					// maxId = -1;
					// }
					personController.addEmptyPerson();
					// System.out.println("maxId for "
					// + jtpFormsPane.getClassToCall() + "'s table is: "
					// + maxId);
				}
				// } catch (SQLException e) {
				// JOptionPane.showMessageDialog(MainFrame.this,
				// "Unable getting maxId.", "DB retrieving problem",
				// JOptionPane.ERROR_MESSAGE);
				// }
			}

			@Override
			public void updateCollectionEventOccured() {
				System.out.println("Mainframe's updateEventOccured.");
			}

			@Override
			public void newItemEventOccured() {
				logger.info("Mainframe's 'New Item' button pressed.");
				personFormPanel.enablePersonFields(true);
			}

			/*
			 * @Override public void saveEventOccured() throws SQLException {
			 * System.out.println("saveEvent triggered");
			 * controller.cConnectToDB(); controller.cSaveToDB(); }
			 * 
			 * @Override public void refreshEventOccured() throws SQLException {
			 * System.out.println("refreshEvent triggered");
			 * controller.cConnectToDB(); controller.cLoadFromDB(); }
			 */

		});

		/*
		 * first add a PersonFormListener with the person's data then, trigger
		 * the PersonFormEventOccurred with the ok button append the form's data
		 * into the TextPanel
		 */
		personFormPanel.setPersonFormListener(new PersonFormListener() {
			public void PersonFormEventOccured(PersonDTO e) {
				textPanel.txpAppend("name = " + e.getName() + ", surname = "
						+ e.getSurname() + ", isIndirectClient? "
						+ e.isChkIndirectClient()
						+ ", ItCollateralClient id = "
						+ e.getItCollateralClient().getId()
						+ ", ItCollateralClient desc = "
						+ e.getItCollateralClient() + "\n");

				/*
				 * now, with the controller, I'll transform this data into an
				 * arraylist that will be stored in the model.Person class Then,
				 * I'll refresh the table.
				 */
				personController.addPerson(e);
				personTablePanel.refresh();

			}
		});

		/*
		 * first add a ColorFormListener with the person's data then, trigger
		 * the ColorFormEventOccurred with the ok button append the form's data
		 * into the TextPanel
		 */
		colorFormPanel.setColorFormListener(new ColorFormListener() {
			public void ColorFormEventOccured(ColorFormEvent e) {
				textPanel.txpAppend("color = " + e.getColor() + ", code = "
						+ e.getCode() + "\n");
			}
		});

		/*
		 * first add a SizeFormListener with the person's data then, trigger the
		 * SizeFormEventOccurred with the ok button append the form's data into
		 * the TextPanel
		 */
		sizeFormPanel.setSizeFormListener(new SizeFormListener() {
			public void SizeFormEventOccured(SizeFormEvent e) {
				/*
				 * size and type are textFields processed as Strings. idSize is
				 * an IdText object processed as integer
				 */
				textPanel.txpAppend("size = " + e.getSize() + ", type = "
						+ e.getType() + ", type List's id = "
						+ e.getIt().getId() + ", type List's String = "
						+ e.getIt() + "\n");
			}
		});

		/*
		 * first add a ProductFormListener with the product's data then, trigger
		 * the ProducFormEventOccurred with the ok button append the form's data
		 * into the TextPanel
		 */
		productFormPanel.setProductFormListener(new ProductFormListener() {
			public void ProductFormEventOccured(ProductFormEvent e) {
				/*
				 * vendor code and description are textFields processed as
				 * Strings. idProductType is an IdText object processed as
				 * integer
				 */
				textPanel.txpAppend("Vendor Code = " + e.getProductCode()
						+ ", description = " + e.getProductDescription()
						+ ", product type List's id = " + e.getIt().getId()
						+ ", product type List's String = " + e.getIt()
						+ ", taxable = " + e.getTaxable() + "\n");
			}
		});

		jmiPersonFP.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				if (jmiPersonFP.isSelected()) {
					splitPane.setDividerLocation((int) personFormPanel.getMinimumSize()
							.getWidth() + 10);
				} else {
					splitPane.setDividerLocation(1);
				}
				// fpPerson.setVisible(jmiPersonFP.isSelected());
			}
		});

		jmiProductFP.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				productFormPanel.setVisible(jmiProductFP.isSelected());
			}
		});

		/*
		 * MVC serialization step 3: the methods are ready to be used by the gui
		 * layer. Note, no reference to the model layer is made.
		 */
		jmiImport.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// check if the fileChooser got a positive response
				if (fcMainFrame.showOpenDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION) {
					try {
						personController.loadPeopleFromFile(fcMainFrame
								.getSelectedFile());
						// refresh after loading
						personTablePanel.refresh();
					} catch (ClassNotFoundException | IOException ex) {
						JOptionPane.showMessageDialog(MainFrame.this,
								"No se pudo importar, joven.", "Load error",
								JOptionPane.ERROR_MESSAGE);
						ex.printStackTrace();
					}
				}
			}
		});

		jmiExport.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// check if the fileChooser got a positive response
				if (fcMainFrame.showSaveDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION) {
					try {
						personController.savePeopleToFile(fcMainFrame
								.getSelectedFile());
					} catch (IOException ex) {
						JOptionPane.showMessageDialog(MainFrame.this,
								"No se pudo exportar, joven.", "Load error",
								JOptionPane.ERROR_MESSAGE);
						ex.printStackTrace();
					}
				}
			}
		});

		jmiExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// getting a handle of the mainframe using MainFrame.this
				int click = JOptionPane.showConfirmDialog(MainFrame.this,
						"¿Estás seguro de salir?", "Confirmar salida.",
						JOptionPane.OK_CANCEL_OPTION);
				System.out.println("click = " + click);
				if (click == JOptionPane.OK_OPTION) {
					/*
					 * 2013.03.15 Since I have created a windowListener event to
					 * deal with the program closing, I'll call the
					 * getWindowListeners method that brings an array of
					 * windowListeners from my MainFrame, where the one that I
					 * created will be included.
					 */
					WindowListener[] wl = getWindowListeners();

					for (WindowListener l : wl) {
						// I call the same windowClosing method that I use in my
						// created WindowEvent
						l.windowClosing(new WindowEvent(MainFrame.this, 0));
					}

					// System.exit(0);
				}
			}
		});

		jmiPreferences.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				prefsDiag.setVisible(true);
			}
		});

		personTablePanel.setPersonTableListener(new PersonTableListener() {
			public void rowDeleted(int rowNum) {
				personController.remPerson(rowNum);
			}
		});

		/*
		 * Set custom listener (Preferences Listener) for the Preferences
		 * dialog.
		 */
		prefsDiag.setPreferencesListener(new PreferencesListener() {
			@Override
			public void savePreferences(String userName, String userPassword,
					int portNumber) {
				System.out
						.println("MainFrame receives preferences from the preferencesDialogue: "
								+ userName
								+ ", "
								+ userPassword
								+ ", "
								+ portNumber);
				// adding the preferences
				prefs.put("user", userName);
				prefs.put("password", userPassword);
				prefs.put("port", new Integer(portNumber).toString());
			}

		});

		/*
		 * jtpFormsPane changeListener to know when and which tab is pressed
		 */
		jtpFormsPane.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				setTabByIndex();
			}
		});
	}

	public void setTabByIndex() {
		tabIndex = jtpFormsPane.getSelectedIndex();
		tabDesc = jtpFormsPane.getTitleAt(tabIndex);
		String classToCall[] = { "Color", "Person", "Product", "Size" };
		try {

			if (tabDesc.equals("Colores") && tabIndex == 0) {
				jtpFormsPane.setClassToCall(classToCall[0]);
			}

			if (tabDesc.equals("Personas") && tabIndex == 1) {
				personController.loadPeopleFromDB();
				jtpFormsPane.setClassToCall(classToCall[1]);
			}

			if (tabDesc.equals("Productos") && tabIndex == 2) {
				jtpFormsPane.setClassToCall(classToCall[2]);
			}

			if (tabDesc.equals("Tallas") && tabIndex == 3) {
				jtpFormsPane.setClassToCall(classToCall[3]);
			}
		} catch (SQLException e) {
			System.out.println("SQLException@setTabByIndex: " + e);
		}

		logger.info("Selected tab: #" + tabIndex + " '" + tabDesc
				+ "' - Class to call: '" + jtpFormsPane.getClassToCall() + "'.");
		// System.out.println("Selected tab: #" + tabIndex + " '" + tabDesc
		// + "' - Class to cal: '" + jtpFormsPane.getClassToCall() + "'.");

	}

	private JMenuBar createJMenuBar() {
		// container of all menus
		JMenuBar jmb = new JMenuBar();
		// menus contained
		JMenu jmFile = new JMenu("Archivo"), jmWindow = new JMenu("Ventana"), jmCatalogues = new JMenu(
				"Catálogos");
		;
		// items that menus contain
		JMenuItem jmiOpen = new JMenuItem("Abrir..."), jmiExit = new JMenuItem(
				"Salir.");
		final JCheckBoxMenuItem jmiPersonFP = new JCheckBoxMenuItem("Personas"), jmiProductFP = new JCheckBoxMenuItem(
				"Productos"), jmiSizeFP = new JCheckBoxMenuItem("Tallas"), jmiColorFP = new JCheckBoxMenuItem(
				"Colores ");
		// I set one item selected by default
		jmiPersonFP.setSelected(true);
		// menu file adds open and exit items
		jmFile.add(jmiOpen);
		jmFile.addSeparator();
		jmFile.add(jmiExit);
		// menu catalogues adds color, person, product and size items
		jmCatalogues.add(jmiColorFP);
		jmCatalogues.add(jmiPersonFP);
		jmCatalogues.add(jmiProductFP);
		jmCatalogues.add(jmiSizeFP);
		// menu window adds catalogues
		jmWindow.add(jmCatalogues);
		// menubar adds file and window menus
		jmb.add(jmFile);
		jmb.add(jmWindow);

		/*
		 * jmiPersonFP.addActionListener(new ActionListener() { public void
		 * actionPerformed(ActionEvent e) { if (jmiPersonFP.isSelected()) {
		 * fpPerson.setVisible(true); jmiProductFP.setSelected(false);
		 * fpProduct.setVisible(false); } else if (!jmiPersonFP.isSelected()) {
		 * fpPerson.setVisible(false); } } });
		 * 
		 * jmiProductFP.addActionListener(new ActionListener() { public void
		 * actionPerformed(ActionEvent e) { if (jmiProductFP.isSelected()) {
		 * fpProduct.setVisible(true); jmiPersonFP.setSelected(false);
		 * fpPerson.setVisible(false); } else if (!jmiProductFP.isSelected()) {
		 * fpProduct.setVisible(false); } } });
		 */

		return jmb;
	}

	private void connect() {
		try {
			generalController.connectToDB();
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(MainFrame.this,
					"Cannot connect to the database.", "DB connection problem",
					JOptionPane.ERROR_MESSAGE);
		}
	}

	// pininos de seguridad
	public boolean validaUsuarioYPass() {
		uname = JOptionPane.showInputDialog(this, "Ingrese su usuario",
				"Ingreso de usuario", JOptionPane.OK_OPTION
						| JOptionPane.QUESTION_MESSAGE);
		psswd = JOptionPane.showInputDialog(this, "Ingrese su contraseña",
				"Ingreso de contraseña", JOptionPane.OK_OPTION
						| JOptionPane.QUESTION_MESSAGE);
		if (uname.equals("alx")) {
			if (psswd.equals("4lx")) {
				JOptionPane.showMessageDialog(this, "Usuario = " + uname
						+ ", contraseña = " + psswd + " autorizados.",
						"Autenticación.", JOptionPane.INFORMATION_MESSAGE);
				// System.out.println("Usuario = " + uname + ", contraseña = " +
				// psswd + " autorizados.");
				return true;
			} else {
				JOptionPane.showMessageDialog(this,
						"Usuario o contraseña inválidos.", "Autenticación.",
						JOptionPane.ERROR_MESSAGE);
				// System.out.println("Usuario o contraseña inválidos.");
				return false;
			}
		} else {
			JOptionPane.showMessageDialog(this,
					"Usuario o contraseña inválidos.", "Autenticación.",
					JOptionPane.ERROR_MESSAGE);
			// System.out.println("Usuario o contraseña inválidos.");
			return false;
		}
	}
}
